package com.wu.util;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.symmetric.AES;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

@Slf4j
public class AesUtils {


    /**
     * 加密
     *
     * @param key
     * @param iv
     * @param data
     * @return
     */
    public static String aesEncryption(String key, String iv, String data) {
        String res = "";
        try {
            AES aes = new AES("CBC", "PKCS5Padding",
                    // 密钥，不可更改
                    key.getBytes(),
                    iv.getBytes(StandardCharsets.UTF_8));
            res = Base64.getUrlEncoder().encodeToString(aes.encrypt(data));
        } catch (Exception e){
            log.warn("aes Encryption error %s", e);
        }

        // 加密为16进制表示 使用url code
        return res;
    }

    /**
     * 解密
     * @param key
     * @param iv
     * @param data
     * @return
     */
    public static String aesDecryption(String key, String iv, String data) {
        String res = "";
        try {
            if (ObjectUtil.isEmpty(data)) {
                return res;
            }
            AES aes = new AES("CBC", "PKCS5Padding",
                    // 密钥，不可更改
                    key.getBytes(),
                    iv.getBytes(StandardCharsets.UTF_8));
            res = aes.decryptStr(data);
        } catch (Exception e){
            log.warn("aes Decryption error, %s", e);
        }

        // 加密为16进制表示
        return res;
    }

    public static void main(String[] args) {
        //生产环境
        System.out.println(aesDecryption("87E66A46C846KDE1","87E629A86A8A4AER","MjKn0qC9qpiednb5aVnrl4EfUoH4nct3KjhgeiVSXzPo2E6zlXJeqj0n4A029h8C7--8a6Dq9Luqqk5U_1JjANahhNlYWK3GZCWwEhKwYuIMo-rg0YlIwFRTx506wXHZXeZMVh73lsz9ivIh4IUMJcoSH0TMHVxcM7v-LRNg5D-od7yTg68WGvbuLUM4V1L6RwM_fXtNVtAJqjxIBqpCsw=="));
        //测试环境
        System.out.println(aesEncryption("87E66A46C846EDE1","87E629A86A8A4AE5","musicSearch:0,personalSong:1,searchIntention:0,homeBanner:0,musicLabel:1"));
    }

}
